﻿using System;
using System.Collections.Generic;
using EmbeddedSharp.Core;

namespace EmbeddedSharp.Scripting {

    /// <summary>
    /// The expression
    /// </summary>
    public class ContextExpression : Expression {

        public IContext Context {
            get;
            set;
        }

        private Node[] variables = null;

        public Node[] Variables {
            get {
                return variables;
            }
        }

        public object GetVariableValue(string name) {
            foreach (Node node in variables) {
                if (node.Value == name) {
                    return node.Evaluate();
                }
            }

            return null;
        }

        public void Assign(string name, object value) {
            foreach (Node node in variables) {
                if (node.Value == name) {
                    VariableNode vn = node as VariableNode;
                    if (vn == null) {
                        throw new ArgumentException();
                    }

                    vn.Value = (string)value;
                    break;
                }
            }
        }

        public ContextExpression(string expr)
            : base(expr) {
            this.variables = parser.Variables.ToArray();
        }
    }
}
